/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lcfgly.View;

import com.lcfgly.Interceptor.UploadStatus;
import com.lcfgly.util.ConfigDate;
import com.lcfgly.util.Encode;
import com.lcfgly.util.ImageUtil;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @author lcfgly
 */
@Controller
@RequestMapping("/upload")
public class UploadFile {

    /**
     * 获取上传的进度
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/progress", method = RequestMethod.POST)
    @ResponseBody
    public Map Progress(HttpServletRequest request) {
        UploadStatus status = (UploadStatus) request.getSession().getAttribute("uploadStatus");
        Map result = new HashMap();
        if (status == null) {
            result.put("end", true);
            return result;
        } else {
            int percent = (int) (100 * (double) status.getBytesRead() / (double) status.getContentLength());
            if (percent == 100) {
                result.put("end", true);
            }
            result.put("percent", percent);
            return result;
        }
    }

    /**
     * 截取图片
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/cutimg", method = RequestMethod.POST)
    @ResponseBody
    public Map CutImage(HttpServletRequest request) {
        int x = Integer.valueOf(request.getParameter("x"));
        int y = Integer.valueOf(request.getParameter("y"));
        int w = Integer.valueOf(request.getParameter("w"));
        int h = Integer.valueOf(request.getParameter("h"));
        int width = Integer.valueOf(request.getParameter("width"));
        int height = Integer.valueOf(request.getParameter("height"));
        String path = request.getParameter("src");
        String filename = path.substring(path.lastIndexOf('/') + 1);
        String filetype = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
        File srcfile = new File(ConfigDate.config("imagespath") + "/" + path);
        File outFile = new File(srcfile.getParent() + "/cut/");
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        outFile = new File(outFile, filename);
        try {
            ImageUtil.CutImageWH(srcfile, outFile, filetype, x, y, w, h, width, height);
        } catch (IOException ex) {
            Logger.getRootLogger().error(ex);
            outFile = srcfile;
        }
        Map result = new HashMap();
        new uploadtoftp(outFile, "images/"+path.substring(0, path.lastIndexOf("/")), filename).start();
        result.put("success", true);
        result.put("url", outFile.getPath().substring(ConfigDate.config("imagespath").length()));
        return result;
    }

    /**
     * 上传图片
     *
     * @param files
     * @return
     */
    @RequestMapping(value = "/images", method = RequestMethod.POST)
    @ResponseBody
    public Object images(@RequestParam("imgFile") MultipartFile[] files) {
        if (files.length > 0) {
            if (files.length == 1) {
                return file(files[0], "images");
            } else {
                return files(files, "images");
            }
        } else {
            return "没有上传文件";
        }
    }

    @RequestMapping(value = "/flash", method = RequestMethod.POST)
    @ResponseBody
    public Object moves(@RequestParam("imgFile") MultipartFile[] files) {
        if (files.length > 0) {
            if (files.length == 1) {
                return file(files[0], "media");
            } else {
                return files(files, "media");
            }
        } else {
            return "没有上传文件";
        }
    }

    /**
     * 单个文件上传
     *
     * @param myfile
     * @param type
     * @param size
     * @param path
     * @return
     */
    private HashMap file(MultipartFile myfile, String type) {
        Integer size = Integer.valueOf(ConfigDate.config(type + "size"));
        String path = ConfigDate.config(type + "path");
        HashMap item = new HashMap();
        if (myfile.isEmpty()) {
            item.put("error", 1);
            item.put("message", "上传文件为空");
        } else {
            try {
                String fileName = new String(myfile.getOriginalFilename().getBytes(), "utf-8");
                String filetype = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
                String[] typelist = ConfigDate.config(type).split(",");
                if (!Arrays.asList(typelist).contains(filetype)) {
                    item.put("error", 1);
                    item.put("message", "上传文件扩展名是不允许的扩展名。\\n只允许" + ConfigDate.config(type) + "格式。");
                } else if (myfile.getSize() > size) {
                    item.put("error", 1);
                    item.put("message", "上传文件过大");
                } else {
                    int randomNum = (int) (Math.random() * 1000);
                    Calendar c = Calendar.getInstance();//可以对每个时间域单独修改
                    int year = c.get(Calendar.YEAR);
                    int month = c.get(Calendar.MONTH);
                    int date = c.get(Calendar.DATE);
                    String filedir = year + "/" + month + "/" + date + "/" + randomNum;
                    fileName = Encode.randomString(6) + fileName.hashCode() + "." + filetype;
                    File dir = new File(path + "/" + filedir);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(dir, fileName));
                    item.put("error", 0);
                    item.put("url", filedir + "/" + fileName);
                }
            } catch (IOException ex) {
                Logger.getRootLogger().error("文件上传失败! ", ex);
                item.put("error", 1);
                item.put("url", "文件上传失败");
            }
        }
        return item;
    }

    /**
     * 多文件上传
     *
     * @param files 上传的文件数据
     * @param type 上传的文件类型（extMap中的key值）
     * @param size 上传的大小限制
     * @param path 上传的路径
     * @return
     */
    private List<HashMap> files(MultipartFile[] files, String type) {
        List<HashMap> result = new ArrayList<HashMap>();
        for (MultipartFile myfile : files) {
            result.add(file(myfile, type));
        }
        return result;
    }

    @RequestMapping("/file_list_json")
    @ResponseBody
    public Object file_list_json(HttpServletRequest request) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        //根目录路径，可以指定绝对路径，比如 /var/www/attached
        String rootPath = request.getServletContext().getRealPath("/") + "uploads/";
        //根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
        String rootUrl = request.getContextPath() + "/uploads/";
        String dir = request.getParameter("dir");
        if (dir != null) {
            if (!Arrays.<String>asList(new String[]{"images", "flash", "media", "file"}).contains(dir)) {
                return "路径不正确，请确认路径.";
            }
            rootPath += dir + "/";
            rootUrl += dir + "/";
            File saveDirFile = new File(rootPath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }
        }
        //根据path参数，设置各路径和URL
        String path = request.getParameter("path") != null ? request.getParameter("path") : "";
        String currentPath = rootPath + path;
        String currentUrl = rootUrl + path;
        String currentDirPath = path;
        String moveupDirPath = "";
        if (!"".equals(path)) {
            String str = currentDirPath.substring(0, currentDirPath.length() - 1);
            moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
        }
        //排序形式，name or size or type
        String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";
        //不允许使用..移动到上一级目录
        if (path.indexOf("..") >= 0) {
            return "你没有权限浏览上一级目录";
        }
        //最后一个字符不是/
        if (!"".equals(path) && !path.endsWith("/")) {
            return "Parameter is not valid.";
        }
        //目录不存在或不是目录
        File currentPathFile = new File(currentPath);
        if (!currentPathFile.isDirectory()) {
            return "目录不存在";
        }
        List<HashMap<String, Object>> fileList = new ArrayList<HashMap<String, Object>>();
        if (currentPathFile.listFiles() != null) {
            for (File file : currentPathFile.listFiles()) {
                HashMap<String, Object> hash = new HashMap<String, Object>();
                String fileName = file.getName();
                if (file.isDirectory()) {
                    hash.put("is_dir", true);
                    hash.put("has_file", (file.listFiles() != null));
                    hash.put("filesize", 0L);
                    hash.put("is_photo", false);
                    hash.put("filetype", "");
                } else if (file.isFile()) {
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    hash.put("is_dir", false);
                    hash.put("has_file", false);
                    hash.put("filesize", file.length());
                    hash.put("is_photo", Arrays.<String>asList(ConfigDate.config("images").split(",")).contains(fileExt));
                    hash.put("filetype", fileExt);
                }
                hash.put("filename", fileName);
                hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
                fileList.add(hash);
            }
        }
        if ("size".equals(order)) {
            Collections.sort(fileList, new SizeComparator());
        } else if ("type".equals(order)) {
            Collections.sort(fileList, new TypeComparator());
        } else {
            Collections.sort(fileList, new NameComparator());
        }
        result.put("moveup_dir_path", moveupDirPath);
        result.put("current_dir_path", currentDirPath);
        result.put("current_url", currentUrl);
        result.put("total_count", fileList.size());
        result.put("file_list", fileList);
        return result;
    }

    /**
     * 按文件名排序
     */
    public class NameComparator implements Comparator {

        @Override
        public int compare(Object a, Object b) {
            HashMap hashA = (HashMap) a;
            HashMap hashB = (HashMap) b;
            if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));
            }
        }
    }

    /**
     * 大小排序
     */
    public class SizeComparator implements Comparator {

        @Override
        public int compare(Object a, Object b) {
            HashMap hashA = (HashMap) a;
            HashMap hashB = (HashMap) b;
            if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {
                    return 1;
                } else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    }

    /**
     * 按类型排序
     */
    public class TypeComparator implements Comparator {

        @Override
        public int compare(Object a, Object b) {
            HashMap hashA = (HashMap) a;
            HashMap hashB = (HashMap) b;
            if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
                return -1;
            } else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
                return 1;
            } else {
                return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));
            }
        }
    }

    /**
     * 上传文件到其他服务器
     */
    public class uploadtoftp extends Thread {

        private final File myfile;
        private final String dir;
        private final String filename;

        public uploadtoftp(File myfile, String dir,String filename) {
            this.myfile = myfile;
            this.dir = dir;
            this.filename=filename;
        }

        @Override
        public void run() {
             InputStream in = null;
            OutputStream out = null;
            try {
                String file = ConfigDate.config("ftpurl") + "/" +dir;
                SmbFile sb = new SmbFile(file);
                if (!sb.exists()) {
                    sb.mkdirs();
                }
                sb.canWrite();
                SmbFile s = new SmbFile(file+"/"+filename);
                in = new BufferedInputStream(new FileInputStream(myfile));
                out = new BufferedOutputStream(new SmbFileOutputStream(s, true));
                byte[] buffer = new byte[1024];
                while (in.read(buffer) != -1) {
                    out.write(buffer);
                }
            } catch (IOException e) {
                Logger.getRootLogger().error("文件上传出错! ", e);
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException e) {
                    Logger.getRootLogger().error("文件流关闭出错! ", e);
                }
            }
        }
        

    }

}
